package com.lam.common.components.dict.interceptor;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.core.annotation.AnnotationUtils;

import com.lam.common.components.dict.annotation.Dict;
import com.lam.common.utils.BeanUtil;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.SpringUtils;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.sql.SqlUtil;

public class DictScanUtil {
	
	public static void addTableList(List<String> list){
		if(CollectionUtil.isNotEmpty(list)) {
			addTable(list);
		}
	}
	
	public static void scanTableList(String pattern){
		
		List<Class<?>> list = SpringUtils.scanClass(pattern);
		if(CollectionUtil.isEmpty(list)) {
			return ;
		}
		
		Set<String> tableNameSet = new HashSet<>();
		for (Class<?> clazz : list) {
			List<Field> fieldList = BeanUtil.getBusinessFields(clazz);
			for (Field field : fieldList) {
				Dict dict = AnnotationUtils.getAnnotation(field, Dict.class);
				if(dict != null && StringUtils.isNotBlank(dict.tableName())) {
					tableNameSet.add(dict.tableName());
				}
			}
		}
		addTable(tableNameSet);
	}
	
	private static void addTable(Collection<String> list) {
		for (String table : list) {
			if(StringUtils.isBlank(table)) {
				continue;
			}
			if(table.toLowerCase().contains("select ")) {
				DictMybatisInterceptor.tableNameSet.addAll(SqlUtil.getTableNameBySql(table));
			}else {
				DictMybatisInterceptor.tableNameSet.add(table);
			}
		}
	}

}
